package cn.cool.infrastructure.adapter.port;

import cn.cool.domain.trade.adapter.port.ITradePort;
import cn.cool.domain.trade.model.entity.NotifyTaskEntity;
import cn.cool.infrastructure.gateway.GroupBuyNotifyService;
import cn.cool.infrastructure.redis.IRedisService;
import cn.cool.types.enums.NotifyTaskHTTPEnumVO;
import cn.hutool.core.util.StrUtil;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class TradePort implements ITradePort {
    @Resource
    private GroupBuyNotifyService groupBuyNotifyService;
    @Resource
    private IRedisService redisService;

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTaskEntity) throws Exception {
        RLock lock = redisService.getLock(notifyTaskEntity.lockKey());
        try {
            if (lock.tryLock(3, 0, TimeUnit.SECONDS)) {
                if (StrUtil.isBlank(notifyTaskEntity.getNotifyUrl())) {
                    return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                }
                return groupBuyNotifyService.groupBuyNotify(notifyTaskEntity.getNotifyUrl(), notifyTaskEntity.getParameterJson());
            }
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        } catch (Exception e) {
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        } finally {
            lock.unlock();
        }
    }
}
